import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { FormInstance } from 'antd/lib/form';
import {
  Modal,
  Button,
  Form,
  message,
  Row,
  Col,
  Upload,
  Input,
  DatePicker,
  Select,
  InputNumber,
} from 'antd';
import PropTypes from 'prop-types';
import { transferOption } from '@/support/utils';

const FormItem = Form.Item;
const mapStateToProps = (state: any) => ({
  ControlBoxMng: state.ControlBoxMng,
});
const enumTypeOption = [
  { label: '正常', value: 0 },
  { label: 'VIN不存在', value: 1 },
  { label: 'VIN已被其他车队关联', value: 2 },
  { label: 'VIN已关联', value: 3 },
  { label: 'VIN异常', value: 4 },
];
class BindModal extends PureComponent<any, any> {
  formRef = React.createRef<FormInstance>();
  static contextTypes = {
    permissions: PropTypes.array,
    dicData: PropTypes.object,
  };

  constructor(props: any) {
    super(props);
    this.state = {
      loading: false,
      vinOption: [],
    };
  }
  componentDidUpdate(prevProps: any) {
    const { modalVisible, formData, dispatch } = this.props;

    if (modalVisible && modalVisible !== prevProps.modalVisible) {
      if (typeof formData.sid === 'number') {
        this.initBindVin();
      }
      dispatch({
        type: 'FleetMng/getData',
        payload: {
          url: '/msalcohollock/vehicle/user/list', //msalcohollock/vehicle/user/list 查看用户权限下的车辆列表
        },
        callback: (res: any) => {
          this.setState({ vinOption: res.data?.map(t => ({ label: t.vin, value: t.vin })) ?? [] });
        },
      });
    }
  }

  componentWillMount() {
    // 获取品牌数据
  }
  handleSubmit = () => {
    this.formRef.current?.submit();
  };

  onFinish = (values: any) => {
    const { formData, dispatch, freshPage } = this.props;
    let postData = {
      fleetSid: formData.sid,
      vinList: values.vinList ?? []
    };
    this.setState({
      loading: true,
    });
    dispatch({
      type: 'FleetMng/postObj',
      payload: {
        url: '/msalcohollock/fleet/vehicle/checkandbind',
        ...postData,
      },
      callback: (res: any) => {
        const data = res.data?.checkList ?? [];
        if (res.statusCode === '0' && res.data?.checkResult === 0) {
          message.success('编辑成功');
          this.close();
          freshPage();
        } else{
          const enumTypeLab = enumTypeOption.map(t=>t.label)
          data.forEach(t=>{
            t.result!==0 && message.warning(`车辆 '${t.vin}' ${enumTypeLab[t.result]}`)
          })
        }
      },
    }).finally(() =>
      this.setState({
        loading: false,
      }),
    );
  };

  close = () => {
    const { closeModal } = this.props;
    this.formRef.current && this.formRef.current.resetFields();
    closeModal();
  };

  //获取已关联vin并设置
  initBindVin = () => {
    const { formData, dispatch } = this.props;

    const postData = {
      sid: formData.sid,
    };
    dispatch({
      type: 'FleetMng/getData',
      payload: {
        url: '/msalcohollock/fleet/vehicle/list',
        ...postData,
      },
      callback: (res: any) => {
        const list = res.data ?? [];
        this.formRef &&
          this.formRef.current?.setFieldsValue({
            vinList: list.map(t => t.vin),
          });
      },
    });
  };
  render() {
    const { loading, vinOption } = this.state;
    const { modalVisible } = this.props;
    const footer = (
      <div>
        <Button size="small" onClick={this.close}>
          取消
        </Button>
        <Button size="small" loading={loading} onClick={this.handleSubmit} type="primary">
          确定
        </Button>
      </div>
    );
    return (
      <Modal
        title={'关联车辆'}
        footer={footer}
        visible={modalVisible}
        width={450}
        onCancel={this.close}
      >
        <Row>
          <Form style={{ width: '100%' }} onFinish={this.onFinish} ref={this.formRef}>
            <Col>
              <FormItem
                label="VIN"
                colon={false}
                name="vinList"
                rules={[{ required: true, message: '请输选择车辆' }]}
              >
                <Select
                  showSearch
                  placeholder="请选择"
                  allowClear
                  style={{ width: '100%' }}
                  // getPopupContainer={triggerNode => triggerNode.parentNode}
                  mode="multiple"
                  options={vinOption}
                >
                  {/* {transferOption(vinOption, ['brandCode', 'brandName'])} */}
                </Select>
              </FormItem>
            </Col>
          </Form>
        </Row>
      </Modal>
    );
  }
}
export default connect(mapStateToProps)(BindModal);
